package com.myjunjie.blog.util;

import java.io.*;
import java.security.GeneralSecurityException;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.*;

public class SendEmailServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 收件人的电子邮件 ID
		String to = "jj4869@qq.com";
		// 发件人姓名
		String name = request.getParameter("name");
		// 发件人邮箱
		String from = request.getParameter("email");
		// 发件信息
		String msg = request.getParameter("message");

		Properties props = new Properties();
		// 开启debug调试
		props.setProperty("mail.debug", "true");
		// 发送服务器需要身份验证
		props.setProperty("mail.smtp.auth", "true");
		// 设置邮件服务器主机名
		props.setProperty("mail.host", "smtp.qq.com");
		// 发送邮件协议名称
		props.setProperty("mail.transport.protocol", "smtp");

		MailSSLSocketFactory sf;
		try {
			sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			props.put("mail.smtp.ssl.enable", "true");
			props.put("mail.smtp.ssl.socketFactory", sf);
		} catch (GeneralSecurityException e) {
			System.out.println("SSL有错误");
			e.printStackTrace();
		}

		// 获取默认的 Session 对象
		Session session = Session.getInstance(props);
		// 设置响应内容类型
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		try {
			Message message = new MimeMessage(session);
			message.setSubject("form " + from +" by " + name);
			
			message.setText(msg);
			message.setFrom(new InternetAddress(to));

	        Transport transport = session.getTransport();
	        transport.connect("smtp.qq.com", to, "asfetxmbjqosbddj");

	        transport.sendMessage(message, new Address[] { new InternetAddress(to) });
	        transport.close();
	        
			// 发送成功
			boolean isSuccess = true;
			out.println(isSuccess);
		} catch (MessagingException mex) {
			System.out.println("发送失败");
			boolean isSuccess = false;
			out.println(isSuccess);
			mex.printStackTrace();
		}
	}
}
